from contextlib import asynccontextmanager
from aiogram import Bot, Dispatcher
from aiogram.fsm.storage.memory import MemoryStorage
from fastapi import FastAPI, Query
from handlers import commands
from config.config import fnsa_telegram_bot_config
import asyncio
import db.etcd as db

bot = Bot(token=fnsa_telegram_bot_config.token)
dp = Dispatcher(storage=MemoryStorage())
dp.include_router(commands.router)

@asynccontextmanager
async def lifespan(app: FastAPI):
    await bot.delete_webhook(drop_pending_updates=True)
    polling_task = asyncio.create_task(dp.start_polling(bot))
    try:
        yield
    finally:
        polling_task.cancel()
        await bot.session.close()

app = FastAPI(lifespan=lifespan)

@app.post("/stocks/news")
async def find_stock_news(stock_name: str = Query(..., description="Название акции для поиска новостей")):
    stock_info = await db.get_info_stock(stock_name.lower())
    if stock_info == "":
        # Retrieve users subscribed to this stock
        user_ids = await db.get_users_subscribed_to_stock(stock_name.lower())
        
        if user_ids:
            for user_id in user_ids:
                # Send message to each subscribed user
                await bot.send_message(user_id, f"Найдена свежая новость для акции {stock_name}")
        
        return {"stock": stock_name, "info": stock_info, "subscribers": user_ids}
    return {"error": "Акция не найдена"}

@app.post("/push_update/")
async def push_update(stock_name: str, update: str):
    # Implement logic to push update to subscribers
    pass

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
